import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
// import { getToken } from '@/utils/auth' // --
import { PcCookie, Key } from '@/utils/cookie' // ++

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// 请求拦截器：携带的 token 字段 request interceptor
service.interceptors.request.use(
  config => {
    // 获取状态仓库中的 token
    // const token = store.getters.token

    // 获取 cookie 中的token，因为没有通过状态管理（由门户网站登录写入同域 cookie 中 )
    const token = PcCookie.get(Key.token)

    // 如果有 token，请求头上带上 token
    if (token) {
      config.headers.token = token // ++
      config.headers.common['Authorization'] = token // ++
    }
    return config
  },
  error => {
    // do something with request error
    console.log('do something with request error')
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器 response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    // 服务器响应失败的处理方法 ++
    if (res.code === 405) {
      Message({
        message: '前端 => 您的身份已过期，请重新登录',
        type: 'error',
        duration: 5 * 1000
      })
    }
    if (res.code !== 20000 && res.code !== 200) {
      console.log('服务器响应失败的处理方法')
      // 如果会重复提示错误信息，可注释这一块
      Message({
        message: res.message || '前端 => Error',
        type: 'error',
        duration: 5 * 1000
      })
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.message || '前端 => Error'))
    } else {
      // 服务器响应成功的处理
      return res
    }
  },
  error => {
    if (error.response && error.response.code === 401) {
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
      window.location.href = `${process.env.VUE_APP_AUTH_CENTER_URL}/refresh?redirectURL=${window.location.href}`
      // return Promise.reject(error)
    }
    // 非 401 状态码，则直接提示信息
    if (error.response && error.response.code !== 401) {
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(error)
    }
    // 401 未认证或者访问令牌过期，要通过刷新令牌获取新的认证信息（这里后端还没做）
    let isLock = true // 防止重复发送刷新请求
    if (isLock && PcCookie.get(Key.refreshToken)) {
      isLock = false // 发送刷新令牌请求后，将些值 设置为 false
      // 跳转到认证中心客户端，实现刷新令牌效果
      window.location.href = `${process.env.VUE_APP_AUTH_CENTER_URL}/refresh?redirectURL=${window.location.href}`
    } else {
      // 没有刷新令牌，则跳转到门户网站进行重新认证
      window.location.href = `${process.env.VUE_APP_AUTH_CENTER_URL}?redirectURL=${window.location.href}`
    }
    return Promise.reject('令牌过期，重新认证')
  }
)

export default service
